package com.elite.km.admin.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.elite.km.admin.dto.AfterBatchUpDTO;
import com.elite.km.admin.dto.ArticleBatchDTO;
import com.elite.km.annotation.AdminApiRestController;
import com.elite.km.bean.Result;
import com.elite.km.bean.SessionStaff;
import com.elite.km.constant.Constants;
import com.elite.km.constant.enums.HttpTaskTypeEnum;
import com.elite.km.controller.BaseController;
import com.elite.km.dto.param.ArticleBatchUpParam;
import com.elite.km.dto.param.TreeNodeParam;
import com.elite.km.entity.HttpTask;
import com.elite.km.entity.TreeNode;
import com.elite.km.helper.DecompressedArticleFileHandler;
import com.elite.km.service.*;
import com.elite.km.thread.DecompressArticleZipThread;
import com.elite.km.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author: sher
 * @since: 2021-01-07
 */
@Slf4j
@Api(tags = "知识节点Admin")
@AdminApiRestController
@RequestMapping(value = "/treeNode", produces = {"application/json; charset=UTF-8"})
public class TreeNodeAdminController extends BaseController {

    @Autowired
    private UtilityService kmUtilityService;
    @Autowired
    private IPrivilegeTreeService privilegeTreeService;
    @Autowired
    private ITreeNodeService treeNodeService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IHttpTaskService httpTaskService;

    @ApiOperation("详情")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result treeNodeCreate(@RequestBody TreeNodeParam treeNodeParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (StringUtil.isEmptyAfterTrim(treeNodeParam.getNodeTitle())) {
            return Result.failed(I18nUtils.get("admin.controller.privilegeTree.createNameIsEmpty", locale));
        }
        if (treeNodeService.countTitleByParent1(treeNodeParam) > 0) {
            return Result.failed(I18nUtils.get("admin.node.articleNameIsExist", locale));
        }
        int count = kmUtilityService.createTreeNode(treeNodeParam);
        if (count > 0) {
            return Result.success(treeNodeParam);
        }
        return Result.failed();
    }

    @ApiOperation("删除普通知识节点")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result treeNodeDelete(@RequestParam String nodeAId) {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String staffId = staff.getStaffId();
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
        List<String> needDeleteTreeNodes = new ArrayList<>();
        List<String> needDeleteArticles = new ArrayList<>();
        articleService.deleteByTree(nodeAId, staffId, epId, needDeleteTreeNodes, needDeleteArticles);
        // 删除知识节点及其子节点(非根知识节点)
        if (treeNodeService.deleteTreeNodeByIds(epId, needDeleteTreeNodes).length >= 0 && articleService.deleteArticleByIds(epId, needDeleteArticles).length >= 0) {
            return Result.success(null, I18nUtils.get("admin.deteleArticleNodeSuccess", locale));
        }
        return Result.failed(I18nUtils.get("admin.deteleArticleNodeFailed", locale));
    }

    @ApiOperation("删除根知识节点")
    @RequestMapping(value = "/deleteRoot", method = RequestMethod.POST)
    public Result treeNodeDeleteRoot(@RequestBody TreeNodeParam treeNodeParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
        String treeNodeId = treeNodeParam.getNodeAId();
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String staffId = staff.getStaffId();
        // 先查询有几条
        int treeRelationCount = privilegeTreeService.countTreeNodeTreeRelationByTreeNodeId(epId, treeNodeId);
        if (treeRelationCount > 1) {
            if (treeNodeService.deleteRootTreeNode(epId, treeNodeParam, false) >= 0) {
                return Result.success(null, I18nUtils.get("admin.moveRootKnowledgeNodeSuccess", locale));
            }
            return Result.failed(I18nUtils.get("admin.moveRootKnowledgeNodeFailed", locale));
        } else if (treeRelationCount == 1) {
            List<String> needDeleteTreeNodes = new ArrayList<>();
            List<String> needDeleteArticles = new ArrayList<>();
            articleService.deleteByTree(treeNodeId, staffId, epId, needDeleteTreeNodes, needDeleteArticles);
            treeNodeService.deleteTreeNodeByIds(epId, needDeleteTreeNodes);
            articleService.deleteArticleByIds(epId, needDeleteArticles);
            if (treeNodeService.deleteRootTreeNode(epId, treeNodeParam, true) >= 0) {
                return Result.success(null, I18nUtils.get("admin.deteleRootKnowledgeNodeSuccess", locale));
            }
            return Result.failed(I18nUtils.get("admin.deteleRootKnowledgeNodeFailed", locale));
        }
        return Result.failed(I18nUtils.get("admin.treeNode.query", locale));
    }

    @ApiOperation("更新基本详情")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result treeNodeUpdate(@RequestBody TreeNodeParam treeNodeParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        log.debug("treeNode: [{}]", treeNodeParam);
        if (treeNodeService.countTitleByParent(treeNodeParam) > 0) {
            return Result.failed(I18nUtils.get("admin.node.articleNameIsExist", locale));
        }
        treeNodeParam.setModifiedDate(ArticleUtil.checkTime());
        boolean isUpdate = treeNodeService.update(treeNodeParam, new LambdaUpdateWrapper<TreeNode>().eq(TreeNode::getNodeAId, treeNodeParam.getNodeAId()));
        if (isUpdate) {
            return Result.success(null);
        } else {
            return Result.failed(I18nUtils.get("admin.updateFailed", locale));
        }
    }

    @ApiOperation("更新父节点")
    @RequestMapping(value = "/updateParent", method = RequestMethod.POST)
    public Result treeNodeUpdateParent(@RequestBody TreeNodeParam treeNodeParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        log.debug("treeNode: [{}]", treeNodeParam);
        int count = treeNodeService.updateParent(treeNodeParam);
        if (count > 0) {
            return Result.success(null);
        } else {
            return Result.failed(I18nUtils.get("admin.updateFailed", locale));
        }
    }

    @ApiOperation("移动到新父节点")
    @RequestMapping(value = "/move2Parent", method = RequestMethod.POST)
    public Result treeNodeMove2Parent(@RequestBody TreeNodeParam treeNodeParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        log.debug("treeNode: [{}]", treeNodeParam);
        // 判断文章是否存在
        if (treeNodeService.countById(treeNodeParam.getNodeAId()) < 1) {
            return Result.failed(I18nUtils.get("admin.controller.articleNode.notExistAndPleaseRefresh", locale));
        }
        if (treeNodeService.countTitleByTreeNode(treeNodeParam) > 0) {
            return Result.failed(I18nUtils.get("admin.treeNode.existNamesakeNode", locale));
        }
        if (treeNodeService.countSamePrivilege(treeNodeParam) > 0) {
            return Result.failed(I18nUtils.get("admin.treeNode.notAllowCrossNode", locale));
        }
        int count = treeNodeService.updateParent2(treeNodeParam);
        if (count > 0) {
            return Result.success(null);
        } else {
            return Result.failed(I18nUtils.get("admin.updateFailed", locale));
        }
    }

    @ApiOperation("详情")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public Result treeNodeDetail(@RequestParam String nodeAId) {
        log.debug("treeNodeId: [{}]", nodeAId);
        return Result.success(kmUtilityService.getTreeNodeDetail(nodeAId));
    }

    @ApiOperation("批量上传文章(待解压)")
    @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data;charset=utf-8")
    public Result articleUpload(@RequestParam("file") MultipartFile file, @RequestParam String pId) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (file == null || file.isEmpty()) {
            return Result.failed(I18nUtils.get("admin.controller.treeNode.uploadFileEmpty", locale));
        }
        String uploadFile = file.getOriginalFilename();
        String extension = FileUtil.getFileExtension(uploadFile);

        if (!ArticleUtil.isArticleFile(extension) && !Constants.FILE_EXTENSION_ZIP.equalsIgnoreCase(extension)) {
            return Result.failed(I18nUtils.get("admin.controller.treeNode.unsafeTypeUploadFailed", locale));
        }
        return Result.success(FileUtil.uploadArticle(file, ArticleUtil.getArticleBatchUpServerPath()));
    }

    @ApiOperation("批量上传后解压导入文件")
    @RequestMapping(value = "/batchUp", method = RequestMethod.POST)
    public Result articleBatchUp(@RequestBody ArticleBatchUpParam articleBatchUpParam) {
        try {
            log.debug("批量上传后解压导入文件...");
            Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
            String uploadFileName = articleBatchUpParam.getFileName();
            log.debug("批量上传后解压导入文件 uploadFileName:" + uploadFileName);

            String ossPath = articleBatchUpParam.getOssPath();
            log.debug("批量上传后解压导入文件 ossPath:" + ossPath);
            log.debug("articleBatchUpParam: [{}]", articleBatchUpParam);

            String fileExtension = FileUtil.getFileExtension(uploadFileName);
            if (!Constants.FILE_EXTENSION_ZIP.equalsIgnoreCase(fileExtension) && !ArticleUtil.isArticleFile(fileExtension)) {
                return Result.failed(I18nUtils.get("admin.treeNode.notAllowArticleType", locale));
            }
            SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
            String staffId = staff.getStaffId();
            String staffName = staff.getStaffName();
            String treeNodeAId = articleBatchUpParam.getTreeNodeId();
            String uploadFilePath = ArticleUtil.getArticleBatchUpServerPath(uploadFileName);
            log.debug("uploadFilePath:{}", uploadFilePath);

            String ngsUrl = StringUtils.isNotEmpty(config.getGetUrl()) ? config.getGetUrl() : config.getDownUrl();
            Map<String, String> mapHeader = new HashMap<String, String>();

            boolean downloadFile = ngsUrl.toLowerCase().startsWith("https") ? HttpsFileDownloader(ngsUrl + Constants.FS_WORD_READ_PATH + ossPath, uploadFilePath) : HttpFileDownloader(ngsUrl + Constants.FS_WORD_READ_PATH + ossPath, uploadFilePath);
            log.debug("批量知识上传文件下载结果:" + downloadFile);
            if (!downloadFile) {
                return Result.failed();
            }
            long timeMills = System.currentTimeMillis();
            String articleBatchDirPath = ArticleUtil.getArticleStoreBatchUpServerPath();
            log.debug("articleBatchDirPath:{}", articleBatchDirPath);

            String taskGuid = UIDUtil.getUUID(true);
            // 记录数据
            HttpTask httpTask = HttpTask.builder().guid(taskGuid).requestUri(request.getRequestURI()).type(HttpTaskTypeEnum.BATCH_UP.getType()).description(staffName + "在知识节点 [" + treeNodeAId + "] " + Constants.HttpTask.BATCH_IMPORT_ARTICLE).createdBy(staffId).status(1).treeNodeId(treeNodeAId).batchUpPath(ArticleUtil.getArticleStoreBatchUpPath(uploadFileName)).batchFile(uploadFileName).build();
            if (!Constants.FILE_EXTENSION_ZIP.equalsIgnoreCase(fileExtension)) {
                httpTask.setArticle(1);
            }
            if (httpTaskService.createHttpTask(httpTask) <= 0) {
                return Result.failed(I18nUtils.get("admin.treeNode.createTaskFailed", locale));
            }

            String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
            String ngsToken = (String) WebUtil.getSessionAttribute(request, Constants.SESSION_NGS_TOKEN);
            Timestamp articleValidateFrom = articleBatchUpParam.getArticleValidateFrom();
            Timestamp articleValidateTo = articleBatchUpParam.getArticleValidateTo();

            if (Constants.FILE_EXTENSION_ZIP.equalsIgnoreCase(fileExtension)) {
                // 批量提交的文章
                ExecutorService executor = Executors.newSingleThreadExecutor();
                DecompressedArticleFileHandler handler = new DecompressedArticleFileHandler(epId, taskGuid, treeNodeAId, "2", staffName, staffId, articleValidateFrom, articleValidateTo);
                executor.execute(new DecompressArticleZipThread(articleBatchUpParam, epId, taskGuid, ngsToken, uploadFilePath, articleBatchDirPath, handler, "gbk"));
                return Result.success(new AfterBatchUpDTO(taskGuid, treeNodeService.listBatchUps(treeNodeAId)));
            } else {
                StringBuilder sb = new StringBuilder(uploadFilePath);
                sb.insert(uploadFilePath.lastIndexOf("."), "_" + timeMills);
                FileUtil.copyFile(uploadFilePath, sb.toString());
                return articleService.saveBatchUpOneArticle(request, taskGuid, articleBatchUpParam, timeMills);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.failed(e.getMessage());
        }
    }

    @ApiOperation("批量导入记录")
    @RequestMapping(value = "/batchList", method = RequestMethod.GET)
    public Result<List<ArticleBatchDTO>> treeNodeArticleBatchList(@RequestParam String taskGuid) {
        log.debug("taskGuid: [{}]", taskGuid);
        return Result.success(kmUtilityService.getTreeNodeArticleBatchList(taskGuid));
    }

    public static boolean HttpFileDownloader(String fileUrl, String savePath) {
        log.debug("批量文件下载附件URL: [{}]", fileUrl);
        log.debug("批量文件下载附件存储地址: [{}]", savePath);
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(savePath);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                inputStream.close();
                System.out.println("文件下载成功！");
            } else {
                System.out.println("无法下载文件。响应码: " + responseCode);
            }
            connection.disconnect();
        } catch (IOException e) {
            log.error("批量文件HTTP下载错误", e);
            return false;
        }
        return true;
    }

    public static boolean HttpsFileDownloader(String fileUrl, String savePath) {
        log.debug("批量文件s下载附件URL: [{}]", fileUrl);
        log.debug("批量文件s下载附件存储地址: [{}]", savePath);
        try {
            // 信任所有证书
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            }};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            URL url = new URL(fileUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(savePath);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                inputStream.close();
                System.out.println("文件下载成功！");
            } else {
                System.out.println("无法下载文件。响应码: " + responseCode);
            }
            connection.disconnect();
        } catch (Exception e) {
            log.error("批量文件HTTPS下载错误", e);
            return false;
        }
        return true;
    }

}